<template>
  <div class="header">
    <div class="parent-button">
      <div class="button-left">
        <el-input
          v-model="searchQuery"
          placeholder="请输入菜品名称"
          clearable
          class="input"
        ></el-input>
        <el-button type="primary" @click="search">搜索</el-button>
      </div>
      <div class="button-right">
        <el-button type="text" style="color: red" @click="handleBatchDelete">批量删除</el-button>
        <el-divider direction="vertical"></el-divider>
        <el-button type="text" @click="handleChangeStatus(
          1,
          multipleSelection.map((item) => item.id)
        )">批量启售</el-button>
        <el-divider direction="vertical"></el-divider>
        <el-button type="text" style="color: red" @click="handleChangeStatus(
          0,
          multipleSelection.map((item) => item.id)
        )">批量停售</el-button>
        <el-button type="warning" @click="addDialogVisible = true">+新建菜品</el-button>
      </div>
    </div>
    <div>
      <el-table ref="multipleTable" :data="paginatedData" border tooltip-effect="dark" style="width: 100%"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="name" label="菜品名称"></el-table-column>
        <el-table-column prop="imageUrl" label="图片">
          <template v-slot="{ row }">
            <el-image style="width: 40px; height: 40px" :src="row.imageUrl" :preview-src-list="[row.imageUrl]">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="categoryName" label="菜品分类"></el-table-column>
        <el-table-column prop="price" label="售价">
          <template v-slot="{ row }">
            {{ `￥${row.price / 100}` }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="售卖状态">
          <template slot-scope="scope">
            {{ scope.row.status ? "启售" : "停售" }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-link type="primary" @click="handleUpdate(scope.row)">修改</el-link>
            <el-divider direction="vertical"></el-divider>
            <el-link type="primary" @click="handleChangeStatus(+!scope.row.status, [scope.row.id])">{{ scope.row.status
              ? "停售" : "启售" }}</el-link>
            <el-divider direction="vertical"></el-divider>
            <el-link type="danger" @click="handleDelete(scope.row.id)">删除</el-link>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableData.length">
      </el-pagination>
    </div>
    <!-- 新建菜品对话框 -->
    <el-dialog title="新建菜品" :visible.sync="addDialogVisible" width="30%" center>
      <el-form ref="ruleForm" :model="addForm" :rules="rules" label-width="120px">
        <el-form-item label="菜品名称" prop="name">
          <el-input v-model="addForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="菜品价格" prop="price">
          <el-input v-model.number="addForm.price" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="菜品分类" prop="categoryName">
          <el-select v-model="addForm.categoryName" placeholder="请选择活动区域">
            <el-option label="川菜" value="川菜"></el-option>
            <el-option label="粤菜" value="粤菜"></el-option>
            <el-option label="鲁菜" value="鲁菜"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="菜品图片" :label-width="formLabelWidth">
          <el-upload class="avatar-uploader" :auto-upload="false" :show-file-list="false" :on-change="handleFileChange"
            :before-remove="beforeRemove">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改菜品对话框 -->
    <el-dialog title="修改菜品" :visible.sync="updateDialogVisible" width="30%" center>
      <el-form ref="updateForm" :model="updateForm" :rules="rules" label-width="120px">
        <el-form-item label="菜品名称" prop="name">
          <el-input v-model="updateForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="菜品价格" prop="price">
          <el-input v-model.number="updateForm.price" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="菜品分类" prop="categoryName">
          <el-select v-model="updateForm.categoryName" placeholder="请选择活动区域">
            <el-option label="川菜" value="川菜"></el-option>
            <el-option label="粤菜" value="粤菜"></el-option>
            <el-option label="鲁菜" value="鲁菜"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="菜品图片" :label-width="formLabelWidth">
          <el-upload class="avatar-uploader" :auto-upload="false" :show-file-list="false" :on-change="handleFileChange"
            :before-remove="beforeRemove">
            <img v-if="updateForm.imageUrl" :src="updateForm.imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="updateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitUpdateForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      formLabelWidth: "120px",
      addForm: {
        name: '',
        price: '',
        categoryName: '',
        image: null,
      },
      updateForm: {
        id: '',
        name: '',
        price: '',
        categoryName: '',
        imageUrl: '',
        image: null,
      },
      rules: {
        name: [
          { required: true, message: '请输入菜品名称', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请输入菜品价格', trigger: 'blur' },
          { type: 'number', message: '价格必须为数字' }
        ],
        categoryName: [
          { required: true, message: '请选择菜品分类', trigger: 'change' }
        ]
      },
      addDialogVisible: false,
      updateDialogVisible: false,
      searchQuery: '',
      tableData: [],
      multipleSelection: [],
      imageUrl: '',
      originalTableData: [], // 用于存储原始数据，以便重置搜索
      currentPage: 1, // 当前页码
      pageSize: 5,   // 每页显示条数
    };
  },
  computed: {
    paginatedData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.tableData.slice(start, end);
    },
    totalPages() {
      return Math.ceil(this.tableData.length / this.pageSize);
    }
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      const res = {
        data: [
          {
            id: 1,
            name: "水煮鱼",
            imageUrl: "/icons/shuizhuyu.jpg",
            categoryName: "川菜",
            price: 4000,
            status: 1,
          },
          {
            id: 2,
            name: "宫保鸡丁",
            imageUrl: "/icons/shuizhuyu.jpg",
            categoryName: "川菜",
            price: 3500,
            status: 1,
          },
          {
            id: 3,
            name: "白切鸡",
            imageUrl: "/icons/shuizhuyu.jpg",
            categoryName: "粤菜",
            price: 5800,
            status: 1,
          }
        ]
      };
      this.tableData = res.data;
      this.originalTableData = [...res.data]; // 保存原始数据
    },
    handleFileChange(file) {
      const isImage = file.raw.type.startsWith('image/');
      const isLt2M = file.raw.size / 1024 / 1024 < 2;

      if (!isImage) {
        this.$message.error('上传文件只能是图片格式!');
        return false;
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
        return false;
      }

      if (this.addDialogVisible) {
        this.imageUrl = URL.createObjectURL(file.raw);
        this.addForm.image = file.raw;
      } else if (this.updateDialogVisible) {
        this.updateForm.imageUrl = URL.createObjectURL(file.raw);
        this.updateForm.image = file.raw;
      }
    },
    beforeRemove() {
      if (this.addDialogVisible) {
        this.imageUrl = '';
        this.addForm.image = null;
      } else if (this.updateDialogVisible) {
        this.updateForm.imageUrl = '';
        this.updateForm.image = null;
      }
      return true;
    },
    submitForm() {
      const newDish = {
        id: this.tableData.length + 1,
        name: this.addForm.name,
        imageUrl: this.imageUrl,
        categoryName: this.addForm.categoryName,
        price: this.addForm.price * 100,
        status: 1,
      };
      this.originalTableData.push(newDish); // 添加到原始数据
      this.tableData = [...this.originalTableData]; // 更新显示数据
      this.currentPage = 1; // 添加成功后跳转到第一页
      this.addDialogVisible = false;
      this.addForm.name = '';
      this.addForm.price = '';
      this.addForm.categoryName = '';
      this.imageUrl = '';
    },
    submitUpdateForm() {
      const index = this.originalTableData.findIndex(item => item.id === this.updateForm.id);
      if (index !== -1) {
        this.originalTableData[index].name = this.updateForm.name;
        this.originalTableData[index].price = this.updateForm.price * 100;
        this.originalTableData[index].categoryName = this.updateForm.categoryName;
        this.originalTableData[index].imageUrl = this.updateForm.imageUrl;
      }
      this.tableData = [...this.originalTableData]; // 更新显示数据
      this.currentPage = 1; // 修改成功后跳转到第一页
      this.updateDialogVisible = false;
      this.updateForm = {
        id: '',
        name: '',
        price: '',
        categoryName: '',
        imageUrl: '',
        image: null,
      };
    },
    search() {
      if (!this.searchQuery.trim()) {
        this.$message.warning('请输入搜索关键词');
        this.tableData = [...this.originalTableData];
        this.currentPage = 1; // 重置到第一页
        return;
      }
      this.tableData = this.originalTableData.filter(item =>
        item.name.includes(this.searchQuery)
      );
      this.currentPage = 1; // 重置到第一页
    },
    handleChangeStatus(status, ids) {
      this.tableData = this.tableData.map(item => {
        if (ids.includes(item.id)) {
          return { ...item, status };
        }
        return item;
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleDelete(id) {
      this.$confirm('此操作将永久删除该菜品, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const index = this.originalTableData.findIndex(item => item.id === id);
        if (index !== -1) {
          this.originalTableData.splice(index, 1);
        }
        this.tableData = this.originalTableData.filter(item => item.id !== id);
        if (this.tableData.length === 0 && this.currentPage > 1) {
          this.currentPage--;
        }
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleBatchDelete() {
      if (this.multipleSelection.length === 0) {
        this.$message({
          type: 'info',
          message: '请选择要删除的菜品'
        });
        return;
      }
      this.$confirm('此操作将永久删除所选菜品, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const deletedIds = this.multipleSelection.map(item => item.id);
        this.originalTableData = this.originalTableData.filter(item => !deletedIds.includes(item.id));
        this.tableData = this.tableData.filter(item => !deletedIds.includes(item.id));
        if (this.tableData.length === 0 && this.currentPage > 1) {
          this.currentPage--;
        }
        this.$message({
          type: 'success',
          message: '批量删除成功!'
        });
        this.multipleSelection = [];
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleUpdate(row) {
      this.updateDialogVisible = true;
      this.updateForm.id = row.id;
      this.updateForm.name = row.name;
      this.updateForm.price = row.price / 100;
      this.updateForm.categoryName = row.categoryName;
      this.updateForm.imageUrl = row.imageUrl;
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
    },
    handleCurrentChange(val) {
      this.currentPage = val;
    }
  },
};
</script>

<style lang="scss" scoped>
.footer {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

.input {
  width: 150px;
  height: 50px;
}

.parent-button {
  display: flex;
  justify-content: space-between;
}

.button-left {
  margin: 10px;
  padding: 10px;
}

.button-right {
  margin: 10px;
  padding: 10px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>